package com.crr.interceptor;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Value("${auth.key}")
    String key;
    @Value("${auth.secret}")
    String secret;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String auth = request.getHeader("Authorization");//获取认证信息
        if (null == auth) {
            //没有认证信息直接返回
            resp(response, "{\"code\":0,\"message\":\"没有授权\"}");
            return false;
        }
        //有认证信息 token传过来格式“Basic ”+base64Encode((username+":"+password).getBytes(charset))
        String[] split = auth.split("\\s+");
        String usernameAndPassword = String.valueOf(Base64Utils.decode(split[1].getBytes()));//解码
        split = usernameAndPassword.split(":");
        String username = split[0];
        String password = split[1];

        if (key.equals(username) && secret.equals(password)) {
            return true;
        }
        resp(response, "{\"code\":0, \"msg\":\"授权信息不正确!\"}");
        return false;
    }

    /**
     * 统一返回接口
     *
     * @param response
     * @param msg
     */
    void resp(HttpServletResponse response, String msg) {
        //设置响应类型和字符编码集
        response.setContentType("application/json;charset=utf-8");
        //获取相应输出流
        try (PrintWriter writer = response.getWriter();) {
            writer.write(msg);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
